# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""

from django import template
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from django.contrib import messages

from django.shortcuts import render
import xlrd
from datetime import datetime, time
from django.views.decorators.csrf import csrf_exempt

from apps.home.models import LackBus


@login_required(login_url="/login/")
def tc_index(request):
    context = {'segment': 'tc-index'}

    html_template = loader.get_template('home/tc-index.html')
    return HttpResponse(html_template.render(context, request))


@login_required(login_url="/login/")
def cctc_file_upload(request):
    context = {'segment': 'cctc-file-upload'}

    html_template = loader.get_template('home/cctc-file-upload.html')
    return HttpResponse(html_template.render(context, request))


@login_required(login_url="/login/")
def index(request):
    context = {'segment': 'index'}

    html_template = loader.get_template('home/index.html')
    return HttpResponse(html_template.render(context, request))


@login_required(login_url="/login/")
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

        load_template = request.path.split('/')[-1]

        if load_template == 'admin':
            return HttpResponseRedirect(reverse('admin:index'))
        context['segment'] = load_template

        html_template = loader.get_template('home/' + load_template)
        return HttpResponse(html_template.render(context, request))

    except template.TemplateDoesNotExist:

        html_template = loader.get_template('home/page-404.html')
        return HttpResponse(html_template.render(context, request))

    except:
        html_template = loader.get_template('home/page-500.html')
        return HttpResponse(html_template.render(context, request))


@login_required(login_url="/login/")
@csrf_exempt
def cctc_file_upload_detail(request):
    if "GET" == request.method:
        return render(request, 'home/cctc-file-upload-detail.html', {})
    else:
        excel_file = request.FILES["excel_file"]

        try:
            wb = xlrd.open_workbook(file_contents=excel_file.read())
        except:
            print('格式有误！')
            messages.error(request, '表格格式有误，请检查后缀名！(仅支持xls)')
            return render(request, 'home/cctc-file-upload-detail.html', {"excel_data": ""})

        table = wb.sheets()[0]

        head_str = list(filter(lambda x: len(x) > 0, table.row_values(1)[0].split(' '), ))
        comp = head_str[0][head_str[0].find('营运企业') + 5:]
        submit_person = head_str[1][head_str[1].find('制表人') + 4:]
        op_date_str = head_str[2][head_str[2].find('营运日期') + 5:]
        submit_date_str = head_str[3][head_str[3].find('上报日期') + 5:]

        print(comp, submit_person, op_date_str, submit_date_str)
        excel_data = table.row_values(1)[0]

        try:
            op_date = datetime.strptime(op_date_str, '%Y年%m月%d日')
            submit_date = datetime.strptime(submit_date_str, '%Y年%m月%d日')
        except:
            print('日期有误！')
            messages.error(request, '表格格式有误，请检查日期！')
            return render(request, 'home/cctc-file-upload-detail.html', {"excel_data": excel_data})

        i = 3  # 数据起始行
        success_bus_info = []
        while table.row_values(i)[0]:
            try:
                seq = int(table.row_values(i)[0])
            except:
                print('序号有误！')
                messages.error(request, '表格格式有误，请检查序号！')
                return render(request, 'home/cctc-file-upload-detail.html', {"excel_data": excel_data})
            lack_bus = LackBus.objects.filter(comp=comp, op_date=op_date, seq=seq)
            if not lack_bus:
                print("adding {:d}".format(seq))
                try:
                    start_time = table.row_values(i)[5]
                    end_time = table.row_values(i)[6]
                    if not start_time:
                        start_time = None
                    else:
                        x = start_time
                        x = int(x * 24 * 3600)  # convert to number of seconds
                        start_time = time(x // 3600, (x % 3600) // 60, x % 60)  # hours, minutes, seconds

                    if not end_time:
                        end_time = None
                    else:
                        x = end_time
                        x = int(x * 24 * 3600)  # convert to number of seconds
                        end_time = time(x // 3600, (x % 3600) // 60, x % 60)  # hours, minutes, seconds
                except:
                    print('时间有误！')
                    messages.error(request, '表格格式有误，请检查起始时间或结束时间！')
                    return render(request, 'home/cctc-file-upload-detail.html', {"excel_data": excel_data})

                try:
                    lack_bus_start_time=table.row_values(i)[12]
                    sup_bus_start_time=table.row_values(i)[13]
                    if not lack_bus_start_time:
                        lack_bus_start_time = None
                    else:
                        if type(lack_bus_start_time) == float:
                            x = lack_bus_start_time
                            x = int(x * 24 * 3600)  # convert to number of seconds
                            lack_bus_start_time = time(x // 3600, (x % 3600) // 60).strftime('%H:%M')  # hours, minutes

                    if not sup_bus_start_time:
                        sup_bus_start_time = None
                    else:
                        if type(sup_bus_start_time) == float:
                            x = sup_bus_start_time
                            x = int(x * 24 * 3600)  # convert to number of seconds
                            sup_bus_start_time = time(x // 3600, (x % 3600) // 60).strftime('%H:%M')  # hours, minutes
                except:
                    print('时间有误！')
                    messages.error(request, '表格格式有误，请检查起始时间或结束时间！')
                    return render(request, 'home/cctc-file-upload-detail.html', {"excel_data": excel_data})
                lack_bus_obj = LackBus(
                    comp=comp,
                    op_date=op_date,
                    seq=seq,
                    line = str(table.row_values(i)[1])[:str(table.row_values(12)[1]).find('.')],
                    word_track=table.row_values(i)[2],
                    plate=table.row_values(i)[3],
                    bus_type="",
                    plate_v2=table.row_values(i)[4],
                    start_time=start_time,
                    end_time=end_time,
                    situation=table.row_values(i)[7],
                    station=table.row_values(i)[8],
                    lack_trip_num=table.row_values(i)[9] if table.row_values(i)[9] else 0,
                    sup_trip_num=table.row_values(i)[10] if table.row_values(i)[10] else 0,
                    total_lack_trip_num=table.row_values(i)[11] if table.row_values(i)[11] else 0,
                    lack_bus_start_time=lack_bus_start_time,
                    sup_bus_start_time=sup_bus_start_time,
                    submit_date=submit_date,
                    category=table.row_values(i)[14],
                    type='非计划'
                )
                lack_bus_obj.save()
                success_bus_info.append((comp, op_date, seq))

            i += 1

        messages.info(request, '表格上传成功')
        return render(request, 'home/cctc-file-upload-detail.html', {"excel_data":success_bus_info})